package cn.tiger.threadPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo {
    public static void main(String[] args) {
        // 示例 1: 基本异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Hello";
        });

        // 示例 2: 结果处理（链式调用）
        CompletableFuture<String> greeting = future
                .thenApply(result -> {
                    System.out.println("Processing result...");
                    return result + " World";
                })
                .exceptionally(ex -> {
                    System.out.println("Error: " + ex.getMessage());
                    return "Error occurred";
                });

        // 示例 3: 最终结果处理
        greeting.thenAccept(finalResult -> 
            System.out.println("Final result: " + finalResult)
        );

        // 等待所有异步操作完成
        try {
            greeting.get(); // 阻塞直到获取结果
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
